import dayjs from 'dayjs'

//递归查找子集
function findTreeTableItem(item, newList, len) {
    let result = false;
    let treeCode = item.treeCode.substr(0, item.treeCode.length - len);
    newList.forEach((itemNew) => {
        if (itemNew.treeCode == treeCode) {
            if (itemNew.children == undefined || itemNew.children == null)
                itemNew.children = [];
            itemNew.children.push(item);
            result = true;
            return;
        } else if (itemNew.children != undefined && itemNew.children != null)
            result = findTreeTableItem(item, itemNew.children, len);
    });
    return result;
}

//递归查找子集
function findTreeSelectItem(item, newList, len, disabled) {
    let result = false;
    let treeCode = item.treeCode.substr(0, item.treeCode.length - len);
    newList.forEach((itemNew) => {
        if (itemNew.id == treeCode) {
            if (itemNew.children == undefined || itemNew.children == null)
                itemNew.children = [];
            itemNew.children.push({id: item.treeCode, label: item.name, disabled: disabled});
            result = true;
            return;
        } else if (itemNew.children != undefined && itemNew.children != null)
            result = findTreeSelectItem(item, itemNew.children, len, disabled);
    });
    return result;
}

export default {
    //两位小数相加，可多个值
    decimalAddition: function () {
        var args = arguments;
        var total = 0.00;
        for (var i = 0; i < args.length; i++) {
            //验证值是否两位小数
            var reg = /^(0|([1-9][0-9]*)|(([0]\.\d{1,2}|[1-9][0-9]*\.\d{1,2})))$/;
            if (!reg.test(args[i])) {
                continue;//验证错误进入下一个循环
            }
            total = (total * 1000 + parseFloat(args[i]) * 1000) / 1000;
        }
        return total;
    },
    //两位小数相减
    decimalSubtraction: function () {
        var args = arguments;
        if (args.length == 1) {
            return args[0];
        }
        //验证值是否两位小数
        var reg = /^(0|([1-9][0-9]*)|(([0]\.\d{1,2}|[1-9][0-9]*\.\d{1,2})))$/;
        if (!reg.test(args[0])) {
            args[0] = 0.00;
        }
        if (!reg.test(args[1])) {
            args[1] = 0.00;
        }
        var result = parseFloat(args[0]) - parseFloat(args[1]);
        result = Math.round(parseFloat(result) * 100) / 100;//保留两位小数
        let numStrings = result.toString().split('.');
        let integerFraction = numStrings[0];
        let decimalFraction = '00';
        if (numStrings.length > 1) {
            decimalFraction = numStrings[1] == null ? '00' : numStrings[1].padEnd(2, '0');
        }
        result = parseFloat(`${integerFraction}.${decimalFraction}`);
        return result;
    },
    getDateStr: (date, fmt) => {//日期格式化显示
        if (date) {
            let format = fmt ? fmt : 'YYYY-MM-DD HH:mm:ss';
            let dateM = dayjs(date);
            if (dateM) {
                return dateM.format(format);
            }
        }
        return '';
    },
    formatterLabel: (text, data) => {//格式化环形图label
        let total = 0;
        for (var i = 0, l = data.length; i < l; i++) {
            total += data[i].value;
        }
        return `${text}\n\n${total.toFixed(2)}`;
    },
    //创建树结构表数据
    buildTreeTable: (list, len) => {
        if (len == undefined || len == null)
            len = 5;
        let newList = [];
        list.forEach((item) => {
            if (item.treeCode.length <= len)
                newList.push(item);
            else if (findTreeTableItem(item, newList, len) == false) {
                newList.push(item);
            }
        });
        return newList;
    },
    //创建数结构下拉选择树结构,源列表、树长度、禁用本身编码、只禁用本身
    buildTreeSelect: (list, len, self, selfOnly) => {
        if (len == undefined || len == null)
            len = 5;
        let newList = [];
        list.forEach((item) => {
            let disabled = false;
            if (selfOnly) {
                if (item.treeCode == self)
                    disabled = true;
            } else {
                if (item.treeCode.indexOf(self) == 0)
                    disabled = true;
            }
            if (item.treeCode.length <= len)
                newList.push({id: item.treeCode, label: item.name, disabled: disabled});
            else if (findTreeSelectItem(item, newList, len, disabled) == false) {
                newList.push({id: item.treeCode, label: item.name, disabled: disabled});
            }
        });
        return newList;
    },
    fileView: (url) => {
        // /a/g
        // url = url.replace(/&/g,"%26");
        // window.open(process.env.VUE_APP_FILE_VIEW_SERVER+'?url='+url);
        window.open(`${process.env.VUE_APP_FILE_VIEW_SERVER}?url=${encodeURIComponent(url)}`);
    },
    /**
     * 格式转树状结构
     * @param   {Array}      原数据
     * @param   {String}    id的字符串
     * @param   {String}    父id的字符串
     * @param   {String}    children的字符串
     * @return  {Array}     数组
     */
    transData: (arr, idStr, pidStr, chindrenStr) => {
        var r = [],
            hash = {},
            id = idStr,
            pid = pidStr,
            children = chindrenStr,
            i = 0,
            j = 0,
            len = arr.length;
        for (; i < len; i++) {
            hash[arr[i][id]] = arr[i];
        }
        for (; j < len; j++) {
            var aVal = arr[j],
                hashVP = hash[aVal[pid]];
            if (hashVP) {
                !hashVP[children] && (hashVP[children] = []);
                hashVP[children].push(aVal);
            } else {
                r.push(aVal);
            }
        }
        return r;
    },
    //删除数组中指定对象
    removeArray: (_arr, _obj) => {
        var length = _arr.length;
        for (var i = 0; i < length; i++) {
            if (_arr[i] == _obj) {
                if (i == 0) {
                    _arr.shift(); //删除并返回数组的第一个元素
                    return _arr;
                }
                else if (i == length - 1) {
                    _arr.pop();  //删除并返回数组的最后一个元素
                    return _arr;
                }
                else {
                    _arr.splice(i, 1); //删除下标为i的元素
                    return _arr;
                }
            }
        }
    }
}
